package org.example.common.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.example.common.JsonResult;
import org.example.common.util.JwtUtils;
import org.example.entity.UserInfoEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        try {
            //请求中有token
            if (StringUtils.isNotBlank(token)) {
                //当前时间
                Date nowDate = new Date();
                //解析token信息
                UserInfoEntity userInfoEntity = JwtUtils.checkJWT(token);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(JSONObject.toJSONString(userInfoEntity), null, null);
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            Integer code = 500;
            String errorMsg = "系统异常";
            if (e instanceof BaseErrorException) {
                BaseErrorException temp = (BaseErrorException) e;
                code = temp.getCode();
                errorMsg = e.getMessage();
            }
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            JsonResult responseEntity = JsonResult.error(errorMsg, null, code + "");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(responseEntity));
            writer.flush();
            writer.close();
        }
    }
}
